package org.iartisan.wechatsdk.mp.pageauth

import java.net.URLEncoder

import org.iartisan.runtime.env.EnvContextConfig
import org.iartisan.runtime.utils.{HttpRequestUtil, StringUtils}
import org.iartisan.wechatsdk.LogAspect
import org.iartisan.wechatsdk.Utils._
import org.iartisan.wechatsdk.common.Constant
import org.iartisan.wechatsdk.mp.pageauth.res.{PageAuthAccessToken, WechatUserInfo}

/**
 * 微信 page auth 部分代码
 *
 * @author King
 * @date 2020-02-09
 */
object WechatPageAuth extends LogAspect{

  private val GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code"

  private val REFRESH_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s"

  private val GETUSERINFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN"

  private val to_snsapi_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect"


  /**
   * 通过code 获取 网页access_token
   *
   * @param code
   */
  def getAccessTokenByCode(code: String) = {
    val appid = EnvContextConfig.get(Constant.wechat_mp_appid)
    val secret = EnvContextConfig.get(Constant.wechat_mp_secret)
    val res = HttpRequestUtil.sendGet(String.format(GET_ACCESS_TOKEN_URL, appid, secret, code))
    //判断res 是否是error
    res.toWechatObj[PageAuthAccessToken]
  }

  /**
   * 刷新token
   *
   * @param refreshToken
   * @return
   */
  def refreshToken(refreshToken: String) = {
    val appid = EnvContextConfig.get(Constant.wechat_mp_appid)
    val res = HttpRequestUtil.sendGet(String.format(REFRESH_TOKEN_URL, appid, refreshToken))
    //返回
    res.toWechatObj[PageAuthAccessToken]
  }


  /**
   * 获取用户信息
   *
   * @param accessToken
   * @param openId
   * @return
   */
  def getUserinfo(accessToken: String, openId: String) = {
    log.info(s"getUserInfo accessToken:${accessToken} openId:${openId}")
    val res = HttpRequestUtil.sendGet(String.format(GETUSERINFO_URL, accessToken, openId))
    log.info("返回内容{}", res.toJson)
    res.toWechatObj[WechatUserInfo]
  }

  def getSnsapiUserinfoUrl(redirectUri: String, stat: String) = {
    getSnsapiUrl("snsapi_userinfo", redirectUri, stat)
  }

  def getSnsapiBaseUrl(redirectUri: String, stat: String) = {
    getSnsapiUrl("snsapi_base", redirectUri, stat)
  }

  private def getSnsapiUrl(_type: String, redirectUri: String, stat: String) = {
    val appid = EnvContextConfig.get(Constant.wechat_mp_appid, "wxb3185eb7535baf52")
    val encodeUrl = URLEncoder.encode(redirectUri, "UTF8")
    String.format(to_snsapi_url, appid, encodeUrl, _type, if (StringUtils.isNotEmpty(stat)) stat else "STATE")
  }
}
